<?php
/**
 *  Class File Uploader
 *
 *  This class is used to upload files on the server.
 *  Only file types that are defined will be uploaded
 *  
 *  We can Upload any type of files and rezize if its an image. 
 *
 *  Config Params:
 * 	Preference 		Default	Value 	Options 	Description
 *	----------------------------------------------------------------------------------------------------------------------
 *	upload_path 	None 			None 		The path to the folder where the upload should be placed. 
 *												The folder must be writable and the path can be absolute or relative.
 *												
 *	allowed_types 	None 			None 		The mime types corresponding to the types of files you allow to be uploaded.
 *												Usually the file extension can be used as the mime type. 
 *												Separate multiple types with a pipe.
 *												
 *	overwrite 		FALSE 			TRUE/FALSE  If set to true, if a file with the same name as the one you are 
 *									(boolean)	uploading exists, it will be overwritten. 
 *												If set to false, a number will be appended to the filename 
 *												if another with the same name exists.
 *												
 *	max_size 		0 				None 		The maximum size (in kilobytes) that the file can be. 
 *												Set to zero for no limit. Note: Most PHP installations have their own limit,
 *												as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default.
 *												
 *	max_width 		0 				None 		The maximum width (in pixels) that the file can be. 
 *												Set to zero for no limit.
 *												
 *	max_height 		0 				None 		The maximum height (in pixels) that the file can be. 
 *												Set to zero for no limit.
 */
class File_Uploader
{
	var $file_name          = 'file_name';
	var $field_name         = 'image';
	var $upload_status		= 0;
	var $errors				= array();
	var $data				= array();
	var $thumb_h			= THUMB_H; // resize thumbnail image - height
	var $thumb_w			= THUMB_W; // resize thumbnail image - width
	var $large_h			= LARGE_H; // resize large image - height
	var $large_w			= LARGE_W; // resize large image - width
	var $medium_h			= MEDIUM_H; // resize large image - height
	var $medium_w			= MEDIUM_W; // resize large image - width
		
   /**
	* Constructor
	*
	* @access    public
	* @param    array    initialization parameters
	*/
	function File_Uploader($params = array())
	{
		$CI =& get_instance(); 	
		$CI->load->library('upload');
		$CI->load->library('image_lib');
		
		if (count($params) > 0)
		{
			$this->initialize($params);        
		}
	
		log_message('debug', "File Uploader Class Initialized");
	}
    
    // --------------------------------------------------------------------
    
    /**
     * Initialize Preferences
     *
     * @access    public
     * @param     array    initialization parameters
     * @return    void
     */
    function initialize($params = array())
    {
        if (count($params) > 0)
        {
            foreach ($params as $key => $val)
            {
                if (isset($this->$key))
                {
                    $this->$key = $val;
                }
            }        
        }
    }
	
	function _set_file_name()
	{
		// set extension
		$file_extension = strtolower(substr(strrchr($_FILES[$this->field_name]["name"],"."),1));
		$this->file_name = $this->file_name . "." . $file_extension;
	}
		
	// --------------------------------------------------------------------
	
	/**
     * Upload File
     *
     * @access    public
	 * @param     array  Config
     * @return    void
     */
    function upload_file($config = array())
    {
		// Determine the current page number.        
       
		$this->CI->upload->initialize($config);		
		
		$this->_set_file_name();
			
		$this->CI->upload->_set_file_name($this->file_name);
		
		if ( ! $this->CI->upload->do_upload($this->field_name) )
		{
			$this->errors["do_upload"][] 	=  $this->CI->upload->display_errors();
			$this->upload_status 			= 0;
		}	
		else
		{
			$this->data   			= array('upload_data' => $this->CI->upload->data());
			$this->upload_status 	= 1;
		}
	}  
	
	// --------------------------------------------------------------------
	
	/**
     * Resize To Thumbnail
     *
     * @access    private
	 * @param     array  Resize Params
     * @return    void
     */
	function _resize_to_thumbnail($resize_params = array())
	{
		if(isset($resize_params) && is_array($resize_params))
		{
			list($width, $height, $type, $attr) = getimagesize($resize_params['upload_path']);			

			if($width < THUMB_W && $height < THUMB_H)
			{
				$resize_params['width'] = $width;
				$resize_params['height'] = $height;
			}
			else
			{
				$resize_params['width'] = $this->thumb_w;
				$resize_params['height'] = $this->thumb_h;				
			}
			$resize_params['create_thumb'] = TRUE;

			$this->_resize($resize_params);
		}
	}
	
	// --------------------------------------------------------------------
	
	/**
     * Resize To Medium Image
     *
     * @access    private
	 * @param     array  Resize Params
     * @return    void
     */
	function _resize_to_medium($resize_params = array())
	{
		if(isset($resize_params) && is_array($resize_params))
		{
			list($width, $height, $type, $attr) = getimagesize($resize_params['upload_path']);			

			if($width < THUMB_W && $height < THUMB_H)
			{
				$resize_params['width'] = $width;
				$resize_params['height'] = $height;
			}
			else
			{
				$resize_params['width'] = $this->medium_w;
				$resize_params['height'] = $this->medium_h;		
			}
			
			$resize_params['create_thumb'] = TRUE;
			$this->_resize($resize_params);
		}		
	}
	
	// --------------------------------------------------------------------
	
	/**
     * Resize To Large Image
     *
     * @access    private
	 * @param     array  Resize Params
     * @return    void
     */
	function _resize_to_large($resize_params = array())
	{
		if(isset($resize_params) && is_array($resize_params))
		{
			$resize_params['width'] = $this->large_w;
			$resize_params['height'] = $this->large_h;
			$resize_params['create_thumb'] = TRUE;
			$this->_resize($resize_params);
		}
	}
	
	// --------------------------------------------------------------------
	
	/**
     * Resize
     *
     * @access    private
	 * @param     array  Resize Params
     * @return    void
     */
	function _resize($params = array())
	{		
     	$config_r['image_library'] = 'gd2';
		$config_r['source_image'] = $params['upload_path'];
		$config_r['create_thumb'] = $params['create_thumb'];
		$config_r['maintain_ratio'] = TRUE;
		$config_r['width'] = $params['width'];
		$config_r['height'] = $params['height'];
		
		$this->CI->image_lib->initialize($config_r);		
		$this->CI->image_lib->resize();
		$this->errors["resize"][] = $this->CI->image_lib->display_errors();

		$this->CI->image_lib->clear();
	}
	
	/**
	 * Move File
	 *
	 * Move the file to the final destination
	 * To deal with different server configurations
	 * we'll use move_uploaded_file().  One of the two should
	 * reliably work in most environments
	 *
	 * @access    private
	 * @param     string
	 * @param     string
     * @return    void
	 */	
	function _move_file($source=NULL, $destination=NULL)
	{
		if( is_file($source) && $source != NULL && $destination != NULL)
		{
			@rename($source, $destination);
			
			if(! is_file($destination) )
				$this->errors["move_file"][] = 'could not move the file';
		}		
	}
}
?>